package com.xiaolanshu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaolanshu.entity.User;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.mapper.UserMapper;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.template.OssTemplate;
import com.xiaolanshu.template.SmsTemplate;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 发送短信验证码
     * 实现：发送完成短信验证码后，需要将验证码保存到redis中
     * @param phone
     * @return
     */
    public void sendMsg(String phone) {
        //1.随机生成6位数字
        String code = RandomStringUtils.randomNumeric(6);
        //2.调用template对象，发送手机短信
        smsTemplate.sendSms(phone,code);
        //3.将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));

    }


    //查找用户并判断用户是否存在
    @Override
    public User findUser(String username) {
        //构造条件，数据库是否有该用户名
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",username);
        return userMapper.selectOne(qw);
    }
    //根据笔记id和用户id删除笔记
    @Override
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    //保存用户头像
    @Override
    public String uploadHeadphoto(MultipartFile headphoto) throws Exception {
        //将图片上传到阿里云Oss
        String headPhotoUrl = ossTemplate.upload(headphoto.getOriginalFilename(), headphoto.getInputStream());

        return headPhotoUrl;
    }

    //根据当前用户id查询用户信息
    @Override
    public User findUser(Long userId) {
        //构造查询条件，根据用户id查询
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,userId);
        return userMapper.selectOne(lqw);
    }
    //根据当前登录用户id修改用户资料
    @Override
    public void updateUserInfo(Map param) {
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        //创建User对象接受参数信息
        User user = new User();
        user.setId(userId);
        user.setUsername((String) param.get("username"));
        user.setPassword((String) param.get("password"));
        user.setPhone((String) param.get("phone"));
        user.setHeadphoto((String) param.get("headphoto"));
        user.setGender((Integer) param.get("gender"));
        user.setAge((Integer) param.get("age"));
        user.setIntroduction((String) param.get("introduction"));
        //构建查询条件
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,userId);
        userMapper.update(user,lqw);

    }
    //根据商品总金额扣除用户的余额
    @Override
    public void reduceMoney(Double amounts,Long userId) {
        //构造条件,先查询用户原来的剩余金额
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,userId);
        User user = userMapper.selectOne(lqw);
        //将用户的余额扣除
        user.setMoney(user.getMoney() - amounts);

        userMapper.update(user,lqw);

    }
    //将所有返利金额保存到购买的用户的信息里
    @Override
    public void saveReturnAmount(Double returnAmounts, Long userId) {
        //构造条件,先查询用户原来的待返金额
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,userId);
        User user = userMapper.selectOne(lqw);
        //将原来的待返金额和现在的返利金额相加
        user.setReturnMoney(user.getReturnMoney()+returnAmounts);

        userMapper.update(user,lqw);
    }
    //提现
    @Override
    public void updateMoney(Double returnMoney,Long userId) {

        //构造条件
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,userId);
        User user = userMapper.selectOne(lqw);

        //将待返金额与余额相加
        user.setMoney(user.getMoney()+returnMoney);
        //清空余额
        user.setReturnMoney(0D);

        userMapper.update(user,lqw);

    }

}
